import { AlertController, AlertOptions, ToastController } from '@ionic/angular';
import * as dayjs from 'dayjs';
import { FORMAT, today } from './day';

export const dialogAlert = async (
  alertCtrl: AlertController,
  option: AlertOptions
) => {
  const alert = await alertCtrl.create(
    Object.assign({ buttons: ['确定'] }, option)
  );
  await alert.present();
};

export const dialogPrompt = async (
  alertCtrl: AlertController,
  option: AlertOptions,
  defaultValue = ''
) => {
  const alert = await alertCtrl.create(
    Object.assign(
      {
        inputs: [
          {
            label: '',
            name: 'input',
            value: defaultValue,
            type: 'text',
            placeholder: option.subHeader,
          },
        ],
        buttons: [{ text: '取消', role: 'cancel' }, { text: '确定' }],
      } as AlertOptions,
      option
    )
  );
  await alert.present();

  return await inputClose(alert);
};

const inputClose = async (alert: HTMLIonAlertElement) => {
  const input = alert.querySelector('input');
  input.onkeydown = (ev: KeyboardEvent) => {
    if (ev.key === 'Enter') {
      alert.dismiss({ values: { input: input.value } });
    }
  };

  input.focus();

  const r = await alert.onDidDismiss();
  if (r.role === 'cancel') {
    return '';
  }

  if (r.data) {
    return r.data.values.input;
  }

  return '';
};

export const dialogDate = async (
  alertCtrl: AlertController,
  option: AlertOptions,
  defaultValue = today()
) => {
  const alert = await alertCtrl.create(
    Object.assign(
      {
        inputs: [
          {
            label: '',
            name: 'input',
            value: defaultValue,
            type: 'date',
            min: dayjs().subtract(1, 'y').format(FORMAT),
            max: dayjs().add(1, 'y').format(FORMAT),
            placeholder: option.subHeader,
          },
        ],
        buttons: [{ text: '取消', role: 'cancel' }, { text: '确定' }],
      },
      option
    )
  );
  await alert.present();

  return await inputClose(alert);
};

export const dialogConfirm = async (
  alertCtrl: AlertController,
  option: AlertOptions
) => {
  let ret = false;
  const alert = await alertCtrl.create(
    Object.assign(
      {
        buttons: [
          { text: '取消', role: 'cancel' },
          {
            text: '确定',
            handler: () => (ret = true),
          },
        ],
      } as AlertOptions,
      option
    )
  );

  await alert.present();
  await alert.onDidDismiss();

  return ret;
};

export const toast = async (toastCtrl: ToastController, message: string) => {
  const t = await toastCtrl.create({
    message,
    duration: 2000,
    color: 'dark',
    position: 'top',
    mode: 'ios',
  });

  await t.present();
};
